import React, { useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import './MainLayout.css';
import logo from '../assets/logo.png';

const MainLayout = ({ children }) => {
  const location = useLocation();
  const { t, i18n } = useTranslation('translation');
  const [selectedLanguage, setSelectedLanguage] = useState('en');

  const changeLanguage = (lng) => {
    i18n.changeLanguage(lng, (err) => {
      if (err) {
        console.error('语言切换失败:', err);
      } else {
        console.log('语言已切换到:', lng);
        setSelectedLanguage(lng);
      }
    });
  };

  return (
    <>
      <div className="layout">
        <nav className="navbar">
          <div className="nav-brand">
            <Link to="/" style={{ display: 'flex', alignItems: 'center', textDecoration: 'none' }}>
              <img src={logo} alt="Brand Logo" style={{ verticalAlign: 'middle' }} />
              <span className="nav-brand-text">ProductRank.ai</span>
            </Link>
          </div>
          <div className="nav-links">
            <Link to="/" className={location.pathname === '/' ? 'active' : ''}>{t('nav.news')}</Link>
            <Link to="/products" className={location.pathname.startsWith('/products') ? 'active' : ''}>{t('nav.products')}</Link>
            <Link to="/solutions" className={location.pathname.startsWith('/solutions') ? 'active' : ''}>{t('nav.solutions')}</Link>
            <Link to="/evaluations" className={location.pathname.startsWith('/evaluations') ? 'active' : ''}>{t('nav.evaluations')}</Link>
            <Link to="/contact" className={location.pathname.startsWith('/contact') ? 'active' : ''}>{t('nav.contact')}</Link>
          </div>
          <div className="auth-buttons">
            <Link to="/signin" className="btn btn-signin">{t('nav.signin')}</Link>
            <Link to="/register" className="btn btn-register">{t('nav.register')}</Link>
          </div>
          <div className="language-selector">
            <select
              value={selectedLanguage}
              onChange={(e) => changeLanguage(e.target.value)}
              className="language-dropdown"
            >
              <option value="en">EN</option>
              <option value="zh">中文</option>
            </select>
          </div>
        </nav>
        <main className="main-content">
          {children}
        </main>
      </div>
    </>
  );
};

export default MainLayout;